﻿using System;
using SaleManagement.Web.App_Code;
using SaleManagement.Domains;
using SaleManagement.Services;
using DevExpress.Web.ASPxGridView;
using System.Web.UI.HtmlControls;

namespace SaleManagement.Web.Pages
{
  public partial class Products : BasePage
  {
    #region Properties
    private string m_innerError = string.Empty;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsCallback && !IsPostBack)
      {
        TList<ProductGroup> listProduct = new ProductGroupService().GetAll();
        cbxGroup.DataSource = listProduct;
        cbxGroup.DataBind();

        cbxSearchGroup.DataSource = listProduct;
        cbxSearchGroup.DataBind();
        cbxSearchGroup.Items.Insert(0, new DevExpress.Web.ASPxEditors.ListEditItem("Tất cả",null));

        LoadProducts();
      }
    }

    protected void gvProduct_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Save")
      {
        m_innerError = "Save|" + SaveProduct();
      }
      else if (para[0] == "Delete")
      {
        int id = 0;
        int.TryParse(para[1], out id);
        m_innerError = DeleteProduct(id);
      }
      LoadProducts();
    }

    protected void gvProduct_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvProduct_PageIndexChanged(object sender, EventArgs e)
    {
      LoadProducts();
    }

    protected void gvProduct_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
    {
      if (e.DataColumn.Name == "Command")
      {
        ASPxGridView gvObject = sender as ASPxGridView;
        HtmlImage img = gvObject.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "imgEdit") as HtmlImage;
        if (img != null)
        {
          img.Attributes.Add("onclick", "onEdit(" + e.VisibleIndex + ")");
        }
      }
    }

    #endregion

    #region Methods
    private void LoadProducts()
    {
      string code = null;
      string name = null;
      int? group = null;
      if (!string.IsNullOrEmpty(txtSearchCode.Text.Trim()))
      {
        code = txtSearchCode.Text.Trim();
      }

      if (!string.IsNullOrEmpty(txtSearchName.Text.Trim()))
      {
        name = txtSearchName.Text.Trim();
      }

      if (cbxSearchGroup.Value != null)
      {
        group = Convert.ToInt32(cbxSearchGroup.Value);
      }

      TList<Product> ds = new ProductService().Search(code, name, group);
      gvProduct.DataSource = ds;
      gvProduct.DataBind();
    }

    private string SaveProduct()
    {
      try
      {
        if (cbxGroup.Value == null)
        {
          return "Phải chọn nhóm sản phẩm";
        }
      

        if(string.IsNullOrEmpty(Utilities.SafeString(txtName.Text)))
        {
          return "Phải nhập tên cho sản phẩm";
        }

        ProductService service = new ProductService();
        SaleManagement.Domains.Product product = null;
        if (!string.IsNullOrEmpty(hfProductId.Value))
        {
          int id = -1;
          int.TryParse(hfProductId.Value, out id);
          product = service.GetById(id);
          if (product == null)
          {
            return "Không tìm thấy sản phẩm tương ứng";
          }
          product.UpdateDate = DateTime.Now;
          product.UpdatedBy = CurrentUser.Username;
        }
        else
        {
          product = new SaleManagement.Domains.Product();
          product.CreatedBy = CurrentUser.Username;
          product.CreatedDate = DateTime.Now;
          //product.CurrentQuantity = 0;
        }

        product.Code = Utilities.SafeString(txtCode.Text);
        product.Name = Utilities.SafeString(txtName.Text);
        product.Description = Utilities.SafeString(txtDescription.Text);
        //product.Price = Utilities.ParseInt(txtPrice.Text).HasValue ? Utilities.ParseInt(txtPrice.Text).Value : 0;
        product.MinQuantity = Utilities.ParseInt(txtMinQuantity.Text).HasValue?Utilities.ParseInt(txtMinQuantity.Text).Value:0;
        product.GuaranteePeriod = Utilities.ParseInt(txtGuaranteePeriod.Text).HasValue ? Utilities.ParseInt(txtGuaranteePeriod.Text).Value : 0;
       
        product.GroupId = Convert.ToInt32(cbxGroup.Value);
        service.Save(product);
      }
      catch (Exception ex)
      {
        WriteLog("CustomerList.aspx::Save Customer", ex);
        return "Có lỗi trong quá trình lưu sản phẩm";
      }
      return string.Empty;
    }

    private string DeleteProduct(int id)
    {
      try
      {
        new ProductService().Delete(id);
        return string.Empty;
      }
      catch (Exception ex)
      {
        WriteLog("Product::Delete Customer", ex);
        return "Bạn không thể xóa sản phẩm này.";
      }
    }
    #endregion
  }
}
